package com.mipo;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class Add {
	public static void main(String[] args) throws Exception {
		/*连接到MongoDB服务 如果是远程连接可以替换localhost为服务器所在IP地址
		两个参数分别服务器地和端口*/
		ServerAddress serverAddress = new ServerAddress("172.31.12.54", 22017);
		List<ServerAddress> addrs = new ArrayList<ServerAddress>();
		addrs.add(serverAddress);
		//三个参数分别用户名、数据库名、密码
		MongoCredential credential = MongoCredential.createMongoCRCredential("zsmongo", "third_swap_data", "zsmd@017".toCharArray());
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		credentials.add(credential);
		//通过连接认证获取MongoDB连接
		MongoClient mongoClient = new MongoClient(addrs, credentials);
		MongoDatabase db = mongoClient.getDatabase("third_swap_data");
		MongoCollection<Document> users = db.getCollection("c006");
		add(users);
		
		mongoClient.close();
		
	}
	/*{
	    "_id" : ObjectId("5b20ee98d896373074781180"),
	    "name" : "hoojo",
	    "age" : 50,
	    "sex" : "男",
	    "children" : {
	        "name" : "jack",
	        "age" : 25,
	        "sex" : "男",
	        "grandSon" : [ 
	            {
	                "name" : "kitty",
	                "age" : 2,
	                "sex" : "男"
	            }, 
	            {
	                "name" : "rose",
	                "age" : 5,
	                "sex" : "男"
	            }
	        ]
	    }
	}*/
    public static void add(MongoCollection<Document> users){
    	Document grandSon = new Document();
        grandSon.put("name", "kitty");
        grandSon.put("age", 2);
        grandSon.put("sex", "男");
        Document grandDaught = new Document();
        grandDaught.put("name", "rose");
        grandDaught.put("age", 5);
        grandDaught.put("sex", "男");
        ArrayList<Document> grands = new ArrayList<Document>();
        grands.add(grandSon);
        grands.add(grandDaught);
        Document son = new Document();
        son.put("name", "jack");
        son.put("age", 25);
        son.put("sex", "男");
        son.put("grandSon", grands);
        Document user = new Document();
        user.put("name", "hoojo");
        user.put("age", 50);
        user.put("sex", "男");
        user.put("children", son);
        users.insertOne(user);
    }
}
